//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/dao/home_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/home/column_type_enum.dart';
import 'package:hktk_app/ienum/my/up_load_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/home/resource_model.dart';
import 'package:hktk_app/model/page/resource_page_model.dart';
import 'package:hktk_app/model/subject/paper_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/my_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/home/paper_item_widget.dart';
import 'package:hktk_app/widget/home/resource_item_widget.dart';

/// 更多试卷/资料详细内容展示
class MorePaperPage extends StatefulWidget {
  /// 栏目id
  final String columnId;

  /// 栏目类型
  final ColumnTypeEnum columnType;

  const MorePaperPage({
    super.key,
    required this.columnId,
    required this.columnType,
  });

  @override
  State<MorePaperPage> createState() => _MorePaperPageState();
}

class _MorePaperPageState extends State<MorePaperPage> {
  late BuildContext _context;

  /// 页数
  late int _current;

  /// 条数
  late int _size;

  /// 总数
  late int _total;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 资料对应的数据
  late List<ResourceModel> _listRes;

  /// 试卷对应的数据
  late List<PaperModel> _listPaper;

  /// 列表滑动控制器
  late ScrollController _scrollController;

  /// 加载中，
  late bool _loading;

  /// 加载状态，0：什么都不显示，1：表示加载中，2：表示没有数据了
  late UploadEnum _loadType;

  /// 试卷详情返回监听
  late StreamSubscription<EventPaperDetailClose> _eventPaperClose;

  @override
  void initState() {
    super.initState();

    _current = 1;
    _size = 10;
    _total = 0;
    _loading = false;
    _loadType = UploadEnum.loading;
    _listRes = [];
    _listPaper = [];
    _scrollController = ScrollController();
    _futureInit = _initData();

    // 监听是否滑动到底部，实现上拉加载功能
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadDataInit();
      }
    });

    // 监听试卷详情页是否返回
    _eventPaperClose = eventBus.on<EventPaperDetailClose>().listen((event) {
       if (_listPaper.isNotEmpty) {
        if (event.columnId == widget.columnId) {
          setState(() {
            _listPaper[event.index].recordId = event.recordId;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();

    _scrollController.dispose();
    _eventPaperClose.cancel();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 24),
      child: FutureBuilder<Map<String, dynamic>>(
        future: _futureInit,
        builder: (
            BuildContext context,
            AsyncSnapshot<Map<String, dynamic>> snapshot,
            ) {
          if (snapshot.connectionState == ConnectionState.done) {
            Map<String, dynamic> map = snapshot.data!;
            if (!map["suc"]) {
              WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                ToastUtil.show(context: context, msg: map["msg"]);
              });
            }
            return _content();
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      if (widget.columnType == ColumnTypeEnum.materialInfo) {
        await _initDataRes();
      } else {
        await _initDataPaper();
      }
      int length = _getListLength();
      // 判断数据
      if (length < _size) {
        _loadType = UploadEnum.def;
      } else if (length == _total) {
        _loadType = UploadEnum.noData;
      }
      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 初始化资料方法
  _initDataRes() async {
    DataModel model = dataUtilComm.dataModel;
    ResourcePageModel<ResourceModel> page = await HomeDao.materialByColumnId(
      size: _size,
      current: _current,
      columnId: widget.columnId,
      industryCode: model.industryId,
      examId: model.examId,
      categoryId: model.categoryId,
    );
    _total = page.total ?? 0;
    if (_loading) {
      List<ResourceModel> list = page.records!;
      _listRes.addAll(list);
    } else {
      _listRes = page.records!;
    }
  }

  /// 初始化试卷方法
  _initDataPaper() async {
    ResourcePageModel<PaperModel> pagePaper = await SubjectDao.paperByColumnId(
      size: _size,
      current: _current,
      columnId: widget.columnId,
      countDetail: true,
    );
    _total = pagePaper.total!;
    if (_loading) {
      List<PaperModel> list = pagePaper.records!;
      _listPaper.addAll(list);
    } else {
      _listPaper = pagePaper.records!;
    }
  }

  /// 加载更多数据方法
  void _loadDataInit() {
    if (_loadType == UploadEnum.def) {
      setState(() {
        _loadType = UploadEnum.noData;
      });
    } else if (_loadType == UploadEnum.loading) {
      if (!_loading) {
        _loading = true;
        _current++;
        _initData().then((Map<String, dynamic> map) {
          // 加载完成
          if (!map["suc"]) {
            ToastUtil.show(context: _context, msg: map["msg"]);
          }
          setState(() {
            _loading = false;
          });
        });
      }
    }
  }

  /// 内容显示方法
  Widget _content() {
    bool noData = widget.columnType == ColumnTypeEnum.materialInfo
        ? _listRes.isNotEmpty
        : _listPaper.isNotEmpty;
    if (noData) {
      // 有数据
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.separated(
          itemBuilder: _itemBuilder,
          separatorBuilder: _separatorBuilder,
          itemCount: _getListLength() + 1,
          controller: _scrollController,
        ),
      );
    } else {
      return showNoData();
    }
  }

  /// 显示对应的长度
  int _getListLength() {
    return widget.columnType == ColumnTypeEnum.materialInfo
        ? _listRes.length
        : _listPaper.length;
  }

  /// 内容显示
  Widget? _itemBuilder(BuildContext context, int index) {
    if (index < _getListLength()) {
      if (widget.columnType == ColumnTypeEnum.materialInfo) {
        return _itemBuilderRes(index);
      } else {
        return _itemBuilderPaper(index);
      }
    } else {
      // 提示组件
      return _tipsItem();
    }
  }

  /// 间距
  Widget _separatorBuilder(BuildContext context, int index) {
    return recommendItemSeparator();
  }

  /// 提示组件显示
  Widget? _tipsItem() {
    if (_loadType == UploadEnum.def) {
      return null;
    } else if (_loadType == UploadEnum.loading) {
      // 加载中
      return SizedBox(
        height: 100,
        child: Center(
          child: SizedBox(
            width: 40,
            height: 40,
            child: CircularProgressIndicator(
              strokeWidth: 4,
            ),
          ),
        ),
      );
    } else if (_loadType == UploadEnum.noData) {
      // 没有数据，我是有底线的
      return showListEnd();
    }
    return null;
  }

  /// 资料显示
  Widget? _itemBuilderRes(int index) {
    ResourceModel model = _listRes[index];
    return ResourceItemWidget(
      title: model.title!,
      num: model.watchTime ?? 0,
      subtitle: model.summary ?? "",
      columnId: widget.columnId,
      free: model.freeFlag ?? false,
      resUrl: model.attachmentInfos?[0].path ?? "",
      resId: model.id!,
      videoRes: false,
    );
  }

  /// 试卷显示
  Widget? _itemBuilderPaper(int index) {
    PaperModel model = _listPaper[index];
    return PaperItemWidget(
      title: model.name!,
      num: model.stuCount ?? 0,
      subtitle: model.qcount?.toString() ?? "0",
      columnId: widget.columnId,
      free: model.free ?? false,
      type: MyUtil.getPaperType(model.paperType!),
      paperId: model.id!,
      recordId: model.recordId,
      index: index,
    );
  }
}
